package com.teamwhole.modules.act.web;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.teamwhole.common.mapper.JsonMapper;
import com.teamwhole.common.model.ResultInfo;
import com.teamwhole.common.utils.StringUtils;
import com.teamwhole.modules.act.entity.Act;
import com.teamwhole.modules.act.service.ActTaskService;
import com.teamwhole.modules.act.utils.ActUtils;
import com.teamwhole.modules.sys.utils.UserUtils;

import jersey.repackaged.com.google.common.collect.Lists;
import jersey.repackaged.com.google.common.collect.Maps;

/**
 * 流程个人任务相关Controller
 */
@Component
@Path("/act/task")
@Consumes("application/json;charset=utf-8")
@Produces("application/json;charset=utf-8")
public class ActTaskResource {

	@Autowired
	private ActTaskService actTaskService;
	
	/**
     * 获取流程列表
     * @param category
     * @return
     */
    @Path("list-process")
    @GET
    public Object processList(@QueryParam("category") String category) {
        List<Object[]> list = actTaskService.processList(category);
        List<Map<String, Object>> mapList = Lists.newArrayList();
        for (Object[] obj : list) {
            Map<String, Object> map = Maps.newHashMap();
            String process = JSON.toJSONString((ProcessDefinition) obj[0], ActUtils.getProcessDefinitionFilter());
            String deployment = JSON.toJSONString((Deployment) obj[1], ActUtils.getDeploymentEntityFilter());
            map.put("process", JsonMapper.fromJsonString(process, Map.class));
			map.put("deployment", JsonMapper.fromJsonString(deployment, Map.class));
            mapList.add(map);
        }
        return mapList;
    }
    
	/**
	 * 获取待办列表
	 * @param procDefKey 流程定义标识
	 * @return
	 */
	@Path("list-todo")
    @POST
	public Object todoList(Act act) throws Exception {
		List<Act> list = actTaskService.todoList(act, UserUtils.getUser().getLoginName());
		return list;
	}
	
	/**
     * 获取已办任务(我参与的流程)
     * @param act
     * @return
     */
    @Path("list-historic")
    @POST
    public Object historicList(Act act) {
        Map<String, Object> map = actTaskService.historicList(act, UserUtils.getUser().getLoginName());
        return map;
    }
    
    /**
     * 获取流转历史列表
     * @param act       流程实例
     * @param startAct  开始活动节点名称
     * @param endAct    结束活动节点名称
     * @return
     */
    @Path("list-histoicFlow")
    @POST
    public Object histoicFlow(Act act/*, String startAct, String endAct*/) {
        List<Act> list = Lists.newArrayList();
        if (StringUtils.isNotBlank(act.getProcInsId())) {
            String startAct = act.getParamMap().get("startAct").toString();
            String endAct = act.getParamMap().get("endAct").toString();
            list = actTaskService.histoicFlowList(act.getProcInsId(), startAct, endAct);
        }
        return list;
    }
    
    /**
     * 获取流程表单
     * @param act
     * @return
     */
    @Path("form")
    @POST
    public Object form(Act act) {
        // 获取流程XML上的表单KEY
        String formKey = actTaskService.getFormKey(act.getProcDefId(), act.getTaskDefKey());
        // 获取流程实例对象
        if (act.getProcInsId() != null){
            act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
        }
        Map<String, Object> map = Maps.newHashMap();
        map.put("url", ActUtils.getFormUrl(formKey, act));
        return map;
    }
    
    /**
     * 签收任务
     * @param act
     * @return
     */
    @Path("claim")
    @POST
    public ResultInfo claim(Act act) {
        String userId = UserUtils.getUser().getLoginName();
        actTaskService.claim(act.getTaskId(), userId);
        return ResultInfo.ok();
    }
    
    /**
     * 读取带跟踪的图片
     * @param procDefId
     * @param execId
     * @return
     * @throws Exception
     */
    @Path("trace/photo/{procDefId}/{execId}")
    @GET
    @Produces("image/*")
    public Response tracePhoto(@PathParam("procDefId") String procDefId, @PathParam("execId") String execId) throws Exception {
        InputStream in = actTaskService.tracePhoto(procDefId, execId);
        return Response.ok(in).build();
    }
    
    /**
     * 启动流程
     * @param procDefKey 流程定义KEY
     * @param businessTable 业务表表名
     * @param businessId    业务表编号
     */
    @Path("start")
    @POST
    public ResultInfo start(Act act) {
        actTaskService.startProcess(act.getProcDefKey(), act.getBusinessId(), act.getBusinessTable(), act.getTitle());
        return ResultInfo.ok();
    }
    
    /**
     * 完成任务
     * @param act
     * @return
     */
    @Path("complete")
    @POST
    public ResultInfo complete(Act act) {
        actTaskService.complete(act.getTaskId(), act.getProcInsId(), act.getComment(), act.getVars().getVariableMap());
        return ResultInfo.ok();
    }
    
    /**
     * 删除任务
     * @param taskId 流程实例ID
     * @param reason 删除原因
     */
    @Path("delete")
    @POST
    public ResultInfo delete(Map<String, String> map) {
        String taskId = map.get("taskId");
        String reason = map.get("reason");
        if (StringUtils.isNotBlank(reason)) {
            actTaskService.deleteTask(taskId, reason);
        }
        return ResultInfo.ok();
    }
    
}
